package com.jeeplus.mob.payUtile;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MD5Util
{
  private static String byteArrayToHexString(byte[] b)
  {
    StringBuffer resultSb = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
      resultSb.append(byteToHexString(b[i]));
    }
    return resultSb.toString();
  }
  
  private static String byteToHexString(byte b)
  {
    int n = b;
    if (n < 0) {
      n += 256;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return hexDigits[d1] + hexDigits[d2];
  }
  
  public static String MD5Encode(String origin, String charsetname)
  {
    String resultString = null;
    try
    {
      resultString = new String(origin);
      MessageDigest md = MessageDigest.getInstance("MD5");
      if ((charsetname == null) || ("".equals(charsetname))) {
        resultString = byteArrayToHexString(md.digest(resultString
          .getBytes()));
      } else {
        resultString = byteArrayToHexString(md.digest(resultString
          .getBytes(charsetname)));
      }
    }
    catch (Exception localException) {}
    return resultString;
  }
  
  private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", 
    "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  
  public static boolean isWechatSign(Map<String, String> map, String apiKey)
  {
    StringBuffer sb = new StringBuffer();
    Set es = map.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry)it.next();
      String k = (String)entry.getKey();
      String v = (String)entry.getValue();
      if ((!"sign".equals(k)) && (v != null) && (!"".equals(v)) && (!"key".equals(k))) {
        sb.append(k + "=" + v + "&");
      }
    }
    sb.append("key=" + apiKey);
    
    String sign = MD5Encode(sb.toString(), "utf-8").toUpperCase();
    System.out.println("验证的签名 ------------" + sign);
    
    String validSign = ((String)map.get("sign")).toUpperCase();
    System.out.println("微信端返回的合法签名 ------------" + validSign);
    return validSign.equals(sign);
  }
}
